#!/bin/bash

set -eux

dir="$1/$STAGE_NAME/"
if ! mkdir -p "$dir"; then
    echo "Failed to create \"$dir\":"
    _dir="$dir"
    while [ -n "$_dir" ]; do
        ls -ld "$_dir" || true
        _dir=${_dir%/*}
        if [ -f "$_dir" ]; then
            cat "$_dir"
        fi
    done
    if [ -f "$1" ]; then
        mv "$1"{,."$(date +%s)"}
        if ! mkdir -p "$dir"; then
            echo "Failed to create \"$dir\""
            exit 1
        fi
    fi
fi

notify=false

ci/functional/junit_list_unsuccessful "$STAGE_NAME/*/*/xunit1_results.xml" > "$dir"test_fails
mv subset.txt "$dir"launchable_subset

while IFS=: read -r class test; do
    echo -e "$class $test: \c"
    if ! grep -q "$test" "$dir"launchable_subset; then
        echo -e 'not \c'
        notify=true
    fi
    echo 'predicted'
done < "$dir"test_fails > "$dir"launchable_prediction_results
# wait for the file to show up (to mitigate funniness with our NFS server)
while [ ! -f "$dir"launchable_prediction_results ]; do
    sleep 1
done

if $notify; then
    not_predicted_percent=$(($(grep -c 'not predicted' "$dir"launchable_prediction_results) * 100 /
                             $(grep -c . "$dir"launchable_prediction_results)))
    {
        echo "Test failures found in $BUILD_URL"
        echo "that were not predicted by Launchable:"
        echo
        cat "$dir"launchable_prediction_results
        echo
        env | sort | grep ^CHANGE_
        echo
        echo "See details in $dir."
    } | mail -r "$HOSTNAME"@intel.com -s "Launchable prediction failure: ${not_predicted_percent}%" brian.murrell@intel.com
fi
